#include "work_enviroment.h"
#include "base/command_line.h"
#include "work_channel_manager.h"
#include "resource_dispatcher.h"

namespace dl {

WorkEnviroment::WorkEnviroment(MessageLoop* message_loop) {
	message_loop_ = message_loop;

	io_thread_.reset(new base::Thread("IPCThread"));
	base::Thread::Options options;
	options.message_loop_type = MessageLoop::TYPE_IO;
	io_thread_->StartWithOptions(options);

  resource_dispatcher_.reset(new ResourceDispatcher());

  work_channel_manager_.reset(
      new WorkChannelManager(io_thread_->message_loop(), resource_dispatcher_.get(),
                             base::Bind(&WorkEnviroment::ExitProcess,
                                        base::Unretained(this))));
}

WorkEnviroment::~WorkEnviroment() {

}

void WorkEnviroment::CreateChannel(const std::string& pipe) {
	work_channel_manager_->CreateChannel(pipe);
}

void WorkEnviroment::ExitProcess() {
  resource_dispatcher_->Clear();
	io_thread_->Stop();
	message_loop_->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}

}